package com.biostime.qdingding.modules.qd.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.persistence.Page;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.job.AutoClearJob;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Transrecord;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.TransrecordService;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.utils.UserUtils;

/**
 * 收支记录Controller
 * @author king
 * @version 2015-11-12
 */
@Controller
@RequestMapping(value = "${adminPath}/qd/transrecord")
public class TransrecordController extends BaseController {

	@Autowired
	private TransrecordService transrecordService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private AutoClearJob autoClearJob;
	
	@ModelAttribute
	public Transrecord get(@RequestParam(required=false) String id) {
		Transrecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = transrecordService.get(id);
		}
		if (entity == null){
			entity = new Transrecord();
		}
		return entity;
	}

	@RequiresPermissions("qd:transrecord:restore")
	@RequestMapping(value = {"autoclear"})
	public String autoclear(Transrecord transrecord, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		/**手动扣费**/
		autoClearJob.schedule();
		
		addMessage(redirectAttributes, "手动扣费完成");
		return "redirect:"+Global.getAdminPath()+"/qd/transrecord/?repage";
	}
	
	@RequiresPermissions("qd:transrecord:view")
	@RequestMapping(value = {"list", ""})
	public String list(Transrecord transrecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Transrecord> page = transrecordService.findPage(new Page<Transrecord>(request, response), transrecord); 
		model.addAttribute("page", page);
		return "modules/qd/transrecordList";
	}

	@RequiresPermissions("qd:transrecord:view")
	@RequestMapping(value = "form")
	public String form(Transrecord transrecord, Model model) {
		model.addAttribute("transrecord", transrecord);
		return "modules/qd/transrecordForm";
	}
	
	@RequiresPermissions(value={"qd:transrecord:edit","qd:addtran:edit"},logical = Logical.OR)
	@RequestMapping(value = "invalid") 
	public String invalid(Transrecord transrecord, Model model, RedirectAttributes redirectAttributes) {
		if(transrecord.getInvalid() == 1){
			addMessage(redirectAttributes, "该支付记录已作废");
			return "redirect:"+Global.getAdminPath()+"/qd/transrecord/?repage";
		}else{
			transrecord.setInvalid(1);
		}
		model.addAttribute("transrecord", transrecord);
		return "modules/qd/transrecordInvalid";
	}

	@RequiresPermissions(value={"qd:transrecord:edit","qd:transrecord:add","qd:addtran:edit","qd:addtran:add"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request,Transrecord transrecord, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, transrecord)){
			return form(transrecord, model);
		}
		String from = request.getParameter("from");
		
		User user = UserUtils.getUser();
		
		transrecord.setCenterId(StringUtils.toInteger(user.getCenter().getId()));
		
		//防止充值金额超过合同金额
		if(StringUtils.isEmpty(transrecord.getId())&&transrecord.getType().equalsIgnoreCase("0")){
			List<Transrecord> list =  transrecordService.getContractRecord(transrecord);
			Contract contract = contractService.get(new Contract(String.valueOf(transrecord.getContractId())));
			Double paidAmount =0.0;
			
			for(Transrecord temp :list){
				paidAmount += temp.getMoney();
			}
			Double amount = paidAmount+transrecord.getMoney();
			if(amount > contract.getAmount()){
				addMessage(redirectAttributes, "已超过合同总金额,请查证后再试");
			}else if(amount <= contract.getAmount()){
				transrecordService.save(transrecord);
				addMessage(redirectAttributes, "保存成功");
			}
			if( from != null && from.equals("contract") ){
				return "redirect:"+Global.getAdminPath()+"/qd/contract/?repage";
			}
			return "redirect:"+Global.getAdminPath()+"/qd/transrecord/?repage";
		}
		
		if(transrecord.getInvalid() != null && transrecord.getInvalid() == 1){
			transrecord.setInvalidBy(Integer.valueOf(user.getId()));
			transrecord.setInvalidDate(new Date());
			addMessage(redirectAttributes, "该记录作废成功");
		}
		transrecordService.save(transrecord);
		return "redirect:"+Global.getAdminPath()+"/qd/transrecord/?repage";
	}
	
	@RequiresPermissions("qd:transrecord:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Transrecord transrecord, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				transrecordService.delete(new Transrecord(id));
			}
		}else{
			transrecordService.delete(transrecord);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/qd/transrecord/?repage";
	}

}